package com.lucas.rpc.framework.proxy;

import com.lucas.rpc.framework.entity.RpcRequest;
import com.lucas.rpc.framework.entity.RpcResponse;
import com.lucas.rpc.framework.entity.RpcServiceConfig;
import com.lucas.rpc.framework.transport.RpcTransport;
import com.lucas.rpc.framework.transport.socket.SocketRpcClient;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-12-04 14:27
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RpcClientProxy implements InvocationHandler {

    //通信方式
    private RpcTransport rpcTransport;

    //rpc配置，主要是版本号，确定是接口的哪个实现类
    private RpcServiceConfig rpcServiceConfig;

    public  <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //创建请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parametersType(method.getParameterTypes())
                .parameters(args)
                .version(rpcServiceConfig.getVersion()).build();
        RpcResponse rpcResponse = null;
        //如果是socket方式
        if(rpcTransport instanceof SocketRpcClient){
            rpcResponse = rpcTransport.sendRpcRequest(rpcRequest);
        }


        return rpcResponse.getData();
    }
}
